package com.itmuch.cloud.study.service.impl;

import com.itmuch.cloud.study.entity.Material;
import com.itmuch.cloud.study.entity.Qrcode;
import com.itmuch.cloud.study.service.ItemBarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ItemBarServiceImpl implements ItemBarService{
	
	@Autowired
	private  JdbcTemplate jdbcTemplate;

    /**
     * @Author：    齐丹枫
     * @Date:       2017/3/17
     * @Time:       15:24
     * @Method:     saveItemBar
     * @Param:      [itemCode, barCodes]
     * @Return:     java.lang.String
     *保存物料和二维码
     *
     *
     *
     */

	
	@Override
	public String saveItemBar(Material itemCode,List<Qrcode> barCodes){



		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String sql = null;
		int i = 1;
		Date st = null;
		
		if(itemCode.getMaterialCode() == null || itemCode.getMaterialCode().equals("")){
			return "{\"msg\": \"请填写物料代码\",\"success\": false}";
		}
		
		
		if (itemCode.getSendtime() != null && !itemCode.getSendtime().equals("")) {
			try {
				st = sdf.parse(itemCode.getSendtime());
				sql = "insert into t_material (id,materialcode,barcode,sendtime,sta) values (?,?,?,'"+sdf.format(st)+"','NEW')";
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				return	"{\"msg\": \"发送时间格式错误（yyyyMMddhh24miss Eg:20170111180800）\",\"success\": false}";
			}
		} else {
			sql = "insert into t_material (id,materialcode,barcode,sendtime,sta) values (?,?,?,NOW(),'NEW')";
		}
		
		for (Qrcode ibd : barCodes) {
			if(ibd.getBarcode() == null || ibd.getBarcode().equals("")){
				return "{\"msg\": \"请填写第"+i+"条二维码\",\"success\": false}";
			}
			i++;
		}
		
		//int length = 0;
		
		try {
			insertOption(itemCode,barCodes,sql);
		} catch (Exception e) {
			 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "{\"msg\": \"绑定失败\",\"success\": false}";
		}
		
		
		
		/*if(itemCode.getFlag().equals("0")){
			sql = "insert into t_item_bar (id,code,sendtime,barcode) values (?,?,?,?)";
			try {
				length = executeSql(itemCode, barCodes, sql,itemCode.getFlag());
			} catch (Exception e) {
				return "{\"msg\": \"绑定失败，数据不合法\",\"success\": false}";
			}
			
			
		}else if(itemCode.getFlag().equals("1")){
			sql = "update t_item_bar set code = ?, sendtime = ?, barCode = ? where code = '"+itemCode.getCode()+"' and barcode = ?";
			try {
				length = executeSql(itemCode, barCodes, sql,itemCode.getFlag());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return "{\"msg\": \"更新失败，数据不合法\",\"success\": false}";
			}
			
		}else{
			return "{\"msg\": \"标志位：(0：插入;1：更新)\",\"success\": false}";
		}*/
		return "{\"msg\": \"绑定成功\",\"success\": true}";
	}
	
	/*private int executeSql(ItemBar itemCode,List<ItemBarDetail> barCodes,String sql,String f){
		int[] batchInsert = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				if(f.equals("0")){
					ps.setString(1, UUID.randomUUID().toString());
					ps.setString(2, itemCode.getCode());
					ps.setString(3,itemCode.getSendTime());
					ps.setString(4, barCodes.get(i).getBarCode());
				}else{
					ps.setString(1, itemCode.getCode());
					ps.setString(2,itemCode.getSendTime());
					ps.setString(3, barCodes.get(i).getBarCode());
					ps.setString(4, barCodes.get(i).getBarCode());
				}
			}
			
			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return barCodes.size();
			}
		});
		
		return batchInsert.length;
	}*/

	//批量插入操作
	private void insertOption(Material itemCode,List<Qrcode> barCodes,String sql){
		int[] batchInsert = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				
				ps.setString(1, UUID.randomUUID().toString());
				ps.setString(2, itemCode.getMaterialCode());
				ps.setString(3, barCodes.get(i).getBarcode());
				
			}
			
			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return barCodes.size();
			}
		});
	}


	@Override
	public Material findMaterialBybarCode(String barCode) {
		// TODO Auto-generated method stub
		String sql = "select * from t_material where barcode = '"+barCode+"'";
		 Material material = null;
		try {
			 material = jdbcTemplate.queryForObject(sql, new RowMapper<Material>() {
				@Override
				public Material mapRow(ResultSet rs, int rowNum) throws SQLException {
					Material material = new Material();
					material.setId(rs.getString("id"));
					material.setMaterialCode(rs.getString("materialcode"));
					material.setSendtime(rs.getString("sendtime"));
					material.setStatus(rs.getString("sta"));
					
					return material;
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
		return material;
	}

	@Override
	public boolean updateStatusToBind(String material, String barCode) {
		StringBuffer sBuffer = new StringBuffer("update t_material set sta = 'BIND' where materialcode = '"+material+"' and barcode = '"+barCode+"'");
		int i = jdbcTemplate.update(sBuffer.toString());
		if(i == 1){
			return true;
		}
		return false;
	}
//根据id批量更新二维码的状态
    @Override
	public boolean updateStatusToNew(List<String> ids) {
		// TODO Auto-generated method stub
		if(ids != null && ids.size() != 0){
			String sql = "update t_material set sta = 'NEW' where id =?";
			try {
				int[] batchUpdate = jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
					
					@Override
					public void setValues(PreparedStatement ps, int i) throws SQLException {
						// TODO Auto-generated method stub
						ps.setString(1, ids.get(i));
					}
					@Override
					public int getBatchSize() {
						// TODO Auto-generated method stub
						return ids.size();
					}
				});
				if(batchUpdate != null && batchUpdate.length != 0){
					return true;
				}
				
			} catch (Exception e) {
				// TODO: handle exception
			    e.printStackTrace();
			}
		}
		return false;
	}
	
}
